<template>
  <div id="app">
    <mqtt></mqtt>
    <transition name="slide-fade">
      <router-view v-if="isRouterAlive"/>
    </transition>
    <div class="testWatch hover" @click="watchTest" ref="test">
      实时定位监测
      <div><span>经度：{{lng}}</span></div>
      <div><span>纬度：{{lat}}</span></div>
      <div><span>位置：{{loc}}</span></div>
      <div><span>速度：{{speed}}</span></div>
      <div><span>精度：{{accuracy}}</span></div>
      <div><span>海拔精度：{{altitudeAccuracy}}</span></div>
      <div>
        <dl v-for="item in testlist">{{item.longitude}},{{item.latitude}}</dl>
      </div>
      <div><mu-button color="primary" @click="seeMaps">查看地图</mu-button></div>
    </div>
    <mu-dialog title="定位服务错误！<LOCATION SERVICE ERROR!>" width="600" max-width="80%" :esc-press-close="false" :overlay-close="false" :open.sync="openAlert">
      请打开该软件的定位或位置服务。<br>
      Please open the location or location service of the software.
      <br> يرجى فتح موقع البرنامج أو موقع الخدمة . 
    </mu-dialog>
  </div>
</template>

<script>
import Mqtt from '@/components/mqtt/mqtt'
import api from "@/common/api"
export default {
  name: 'App',
  components: {
    Mqtt
  },
  provide () {
    return {
      reload: this.reload
    }
  },
  data () {
    return {
      isRouterAlive: true,
      firstBack: null,
      iswatchTest: true,
      lat: window.lat,
      lng: window.lng,
      testlist: [],
      wakeLock: null,
      loc: '',
      accuracy: 0,
      altitudeAccuracy: 0,
      openAlert: false,
      speed: 0
    }
  },
  methods: {
    reload () {
      this.isRouterAlive = false;
      this.$nextTick(()=>{
        this.isRouterAlive = true;
      });
    },
    seeMaps () {
      this.$router.push({name:'maps'});
    },
    watchTest(){
      if(this.iswatchTest){
        this.$refs.test.classList.remove('hover')
      }else{
        this.$refs.test.classList.add('hover')
      }
      this.iswatchTest = !this.iswatchTest;
    },
    backAction () {
      // 监听回退事件
      let _this = this;
      function goExit () {
        if (!_this.firstBack) {
            _this.firstBack = new Date().getTime();
            // 提示
            _this.Toast({
                duration: 1000,
                mask: false,
                message: "再按一次退出程序"
            });
            setTimeout(() => {
              _this.firstBack = null;
            }, 1000);
        }else{
          if(new Date().getTime() - _this.firstBack < 1000) {
            plus.runtime.quit();
          }
        }
      }
      plus.key.addEventListener("backbutton", function(){
        if(_this.$route.path === '/home' || _this.$route.path === '/'){
          goExit();
        }else{
          _this.$router.go(-1)
        }
        return false;
      },false);
    },
    watchGeolocation () {
      // 监听实时定位
      let _this = this;
      plus.geolocation.watchPosition(function(p){
        _this.speed = parseFloat(p.coords.speed);
        _this.lat = p.coords.latitude;
        _this.lng = p.coords.longitude;
        _this.loc = p.addresses;
        _this.accuracy = p.coords.accuracy;
        _this.altitudeAccuracy = p.coords.altitudeAccuracy;
        _this.openAlert = false;
        // console.log("App.vue -> 监控中：", JSON.stringify(p));
        // alert("App.vue -> 监控中：" + JSON.stringify(p));

        _this.$store.commit('setGeolocation', {
          latitude: p.coords.latitude,
          longitude: p.coords.longitude,
          speed: p.coords.speed,
          accuracy: p.coords.accuracy,
          altitudeAccuracy: p.coords.altitudeAccuracy,
          addresses: p.addresses
        })

        if(_this.$store.state.user.clientId){
          _this.isGeo();
        }

        // 坐标转换
        // plus.maps.Map.convertCoordinates(new plus.maps.Point(p.coords.longitude, p.coords.latitude), {}, function(event){
        //   var point = event.coord;  // 转换后的坐标值
        //   _this.lat = point.latitude;
        //   _this.lng = point.longitude;
        //   _this.$store.commit('setGeolocation', {
        //     latitude: point.latitude,
        //     longitude: point.longitude,
        //     speed: p.coords.speed
        //   })
        // },function(e){
        //   alert("Failed:"+JSON.stringify(e));
        // });
      }, function(e){
        console.log('定位错误: ' + JSON.stringify(e));
        _this.openAlert = true;
        // alert(JSON.stringify(_this.$store.state.user));
        if(_this.$store.state.user.clientId){
          _this.isGeo();
          // let data = Object.assign({}, _this.$store.state.user,{
          //     content: {
          //       tips: "定位未开启。"
          //     }
          // });
          // /* 发送post请求 */
          // _this.common.reqData(api.app('locationError'), data, res=>{
          //   console.log("定位未开启。 res", res);
          // },err =>{
          //   console.log(err)
          // });
        }
        // alert('定位错误: '+ e.message);
      }, {
        coordsType: "bd09ll",
        enableHighAccuracy: true,
        geocode: true,
        provider:'baidu'
      });
    },
    setKeepAlive(keepAlive){
      if(this.wakeLock){
        if(keepAlive){
          this.wakeLock.acquire();
        }else{
          this.wakeLock.release();
        }
      }
      console.log(this.wakeLock.isHeld());
    },
    createWakeLock(){
      console.log("getLock start");
      let main = plus.android.runtimeMainActivity();
      var BluetoothManager = plus.android.importClass("android.os.PowerManager");  
      let pw = main.getSystemService("power");
      this.wakeLock = pw.newWakeLock(1, plus.runtime.appid + "_lock");
      this.wakeLock.setReferenceCounted(false);
      console.log("getLock end");
    },
    isGeo(){
      var _this = this;
      var context = plus.android.importClass("android.content.Context");
      var locationManager = plus.android.importClass("android.location.LocationManager");
      var main = plus.android.runtimeMainActivity();
      var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
      if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
        _this.openAlert = true;
        let data = Object.assign({}, _this.$store.state.user,{
            content: {
              tips: "定位未开启。"
            }
        });
        /* 发送post请求 */
        _this.common.reqData(api.app('locationError'), data, res=>{
          console.log("定位未开启。 res", res);
        },err =>{
          console.log(err)
        });
        // plus.nativeUI.alert('已关闭定位权限');
        // uni.showModal({
        //   title: '提示',
        //   content: '请打开定位服务功能',
        //   showCancel: false, // 不显示取消按钮
        //   success() {
        //     if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
        //       var Intent = plus.android.importClass('android.content.Intent');
        //       var Settings = plus.android.importClass('android.provider.Settings');
        //       var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        //       main.startActivity(intent); // 打开系统设置GPS服务页面
        //     } else {
        //       console.log('GPS功能已开启');
        //     }
        //   }
        // });
      }
      
      // var pp = plus.navigator.checkPermission('LOCATION');
      // switch(pp){
      //   case 'authorized':
      //     plus.nativeUI.alert('已开启定位权限');
      //   break;
      //   case 'denied':
      //     plus.nativeUI.alert('已关闭定位权限');
      //     send();
      //   break;
      //   case 'undetermined':
      //     plus.nativeUI.alert('未确定定位权限');
      //     send();
      //   break;
      //   case 'unknown':
      //     plus.nativeUI.alert('无法查询定位权限');
      //     send();
      //   break;
      //   default:
      //     plus.nativeUI.alert('不支持定位权限');
      //     send();
      //   break;
      // }
    }
  },
  mounted () {
    let _this = this;
    document.addEventListener("plusready", function(){
      _this.isGeo();
      _this.backAction();
      _this.watchGeolocation();
      plus.device.setWakelock(true); // 设置屏幕常亮
      _this.createWakeLock(); // 创建锁
      _this.setKeepAlive(true); // 设置锁为true
    });
  }
}
</script>

<style>
/* 路由动画三种 */
* {
  margin: 0;
  padding: 0;
}
.slide-fade{
  position: absolute;left:0;right: 0;
}
.slide-fade-enter-active {
  transition: all .5s ease;
}
.slide-fade-leave-active {

  transition: all .1s cubic-bezier(2.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter, .slide-fade-leave-to{
  left:0;
  right: 0;
  transform: scale(0.9);
  opacity: 0;
}
.slide-right-enter-active,
.slide-right-leave-active,
.slide-left-enter-active,
.slide-left-leave-active {
  will-change: transform;
  transition: all 500ms;
  position: absolute;
}
.slide-right-enter {
  opacity: 0;
  transform: translate3d(-100%, 0, 0);
}
.slide-right-leave-active {
  opacity: 0;
  transform: translate3d(100%, 0, 0);
}
.slide-left-enter {
  opacity: 0;
  transform: translate3d(100%, 0, 0);
}
.slide-left-leave-active {
  opacity: 0;
  transform: translate3d(-100%, 0, 0);
}
/* #app .mu-table th, #app .mu-table td{
  padding-left: 5px;
  padding-right: 5px;
  line-height: 28px;
  height: auto;
} */
.mu-demo-form .mu-form-item-content{
    justify-content: center;
}

.mu-input-help{
    color: red;
}

.flex-header{
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 9999;
}
.content-box{
  width: 100%;
  padding: 45px 0 0;
}

/*下拉选择器*/
.mu-bottom-sheet{
  max-height: 50%;
  overflow-x: hidden;
  overflow-y: auto;
}
.mu-item {
  min-height: 48px;
  height: auto;
}
.mu-item-sub-title, .mu-item-title{
  white-space:inherit;
  height: auto;
}
.mu-switch-checked .mu-switch-thumb{
  -webkit-transform: translate3d(25px,0,0);
  transform: translate3d(25px,0,0);
}
.mu-switch-container{
  width: 50px;
}
.mu-switch-track{
  height:20px;
}
.mu-switch-thumb{
  width: 26px;
  height: 26px;
}
.van-toast{
  font-size: 14px;
  line-height: 1.48;
}
div.van-toast--default{
  width: auto;
  min-width: 120px;
}
.testWatch{
  position: fixed;
  right: 0;
  z-index: 999;
  overflow: auto;
  bottom: 10%;
  background-color: rgba(0, 0, 0, 0.5);
  color: #ffffff;
  width: 250px;
  padding: 10px;
  text-align: right;
}
.testWatch.hover{
  right: -235px;
}
.targetLocation{
  position: fixed;
  top: 10%;
  right: -135px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #ffffff;
  padding: 10px;
  text-align: right;
  padding-left: 25px;
  width: 150px;
  overflow: auto;
}
.targetLocation.hover{
  right: 0;
}
.my-cards{
  margin: 1rem auto 0;
  max-width: 375px; 
}
#mytables .mu-table th, 
#mytables .mu-table td {
    padding-left: 5px;
    padding-right: 5px;
}
html audio{
  position: relative;
  z-index: -11;
  visibility: hidden;
}
</style>
